package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.itheima.common.CustomException;
import com.itheima.common.R;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author msi
 */
@RequestMapping("/common")
@RestController
public class CommonController {

    /**
     * 你的endpoint
     */
    @Value("${reggie.endpoint}")
    private String endpoint;
    /**
     * 阿里云可以获取到
     */
    @Value("${reggie.keyId}")
    private String keyId;
    /**
     * 阿里云可以获取到
     */
    @Value("${reggie.secret}")
    private String secret;
    @Value("${reggie.bucketName}")
    private String bucketName;


    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        if (null==originalFilename){
            throw new CustomException("上传的文件名格式错误");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(new Date());
        String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = dateStr+"/"+ UUID.randomUUID().toString().replace("-", "") + lastName;


        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, secret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        ossClient.putObject(bucketName, fileName, file.getInputStream(), objectMetadata);
        //url有效期
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 7);

        String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
        ossClient.shutdown();
        return R.success(url);
    }

}
